#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
主题系统模块
提供多种界面主题选择功能
"""

import json
import os
from PyQt6.QtWidgets import QApplication, QDialog, QVBoxLayout, QHBoxLayout, QGroupBox, QComboBox, QPushButton, QMessageBox
from PyQt6.QtCore import QObject, pyqtSignal
from PyQt6.QtGui import QPalette, QColor, QAction

class ThemeSystem(QObject):
    """主题系统类"""
    
    # 信号定义
    theme_changed = pyqtSignal(str)  # 主题改变信号
    
    def __init__(self, main_window):
        super().__init__()
        self.main_window = main_window
        self.current_theme = "default"
        self.custom_themes = {}  # 添加自定义主题字典
        self.config_file = os.path.join(os.path.expanduser("~"), ".gofile", "theme_config.json")
        
        # 确保配置目录存在
        os.makedirs(os.path.dirname(self.config_file), exist_ok=True)
        
        # 定义主题配置
        self.themes = {
            "default": {
                "name": "默认主题",
                "description": "系统默认的浅色主题",
                "style": """
                    QMainWindow {
                        background-color: #f0f0f0;
                        color: #000000;
                    }
                    QMenuBar {
                        background-color: #ffffff;
                        color: #000000;
                        border-bottom: 1px solid #d0d0d0;
                    }
                    QMenuBar::item {
                        background-color: transparent;
                        padding: 4px 8px;
                    }
                    QMenuBar::item:selected {
                        background-color: #e0e0e0;
                    }
                    QMenu {
                        background-color: #ffffff;
                        color: #000000;
                        border: 1px solid #d0d0d0;
                    }
                    QMenu::item:selected {
                        background-color: #e0e0e0;
                    }
                    QStatusBar {
                        background-color: #f8f8f8;
                        color: #000000;
                        border-top: 1px solid #d0d0d0;
                    }
                    QTextEdit {
                        background-color: #ffffff;
                        color: #000000;
                        border: 1px solid #d0d0d0;
                        selection-background-color: #3399ff;
                    }
                    QScrollArea {
                        background-color: #ffffff;
                        border: 1px solid #d0d0d0;
                    }
                    QLabel {
                        color: #000000;
                    }
                    QPushButton {
                        background-color: #e8e8e8;
                        color: #000000;
                        border: 1px solid #c0c0c0;
                        padding: 5px 10px;
                        border-radius: 3px;
                    }
                    QPushButton:hover {
                        background-color: #d8d8d8;
                    }
                    QPushButton:pressed {
                        background-color: #c8c8c8;
                    }
                    QSlider::groove:horizontal {
                        border: 1px solid #bbb;
                        background: white;
                        height: 10px;
                        border-radius: 4px;
                    }
                    QSlider::handle:horizontal {
                        background: #3399ff;
                        border: 1px solid #5c5c5c;
                        width: 18px;
                        margin: -2px 0;
                        border-radius: 3px;
                    }
                """
            },
            "dark": {
                "name": "深色主题",
                "description": "护眼的深色主题",
                "style": """
                    QMainWindow {
                        background-color: #2b2b2b;
                        color: #ffffff;
                    }
                    QMenuBar {
                        background-color: #3c3c3c;
                        color: #ffffff;
                        border-bottom: 1px solid #555555;
                    }
                    QMenuBar::item {
                        background-color: transparent;
                        padding: 4px 8px;
                    }
                    QMenuBar::item:selected {
                        background-color: #555555;
                    }
                    QMenu {
                        background-color: #3c3c3c;
                        color: #ffffff;
                        border: 1px solid #555555;
                    }
                    QMenu::item:selected {
                        background-color: #555555;
                    }
                    QStatusBar {
                        background-color: #3c3c3c;
                        color: #ffffff;
                        border-top: 1px solid #555555;
                    }
                    QTextEdit {
                        background-color: #1e1e1e;
                        color: #ffffff;
                        border: 1px solid #555555;
                        selection-background-color: #0078d4;
                    }
                    QScrollArea {
                        background-color: #2b2b2b;
                        border: 1px solid #555555;
                    }
                    QLabel {
                        color: #ffffff;
                    }
                    QPushButton {
                        background-color: #404040;
                        color: #ffffff;
                        border: 1px solid #606060;
                        padding: 5px 10px;
                        border-radius: 3px;
                    }
                    QPushButton:hover {
                        background-color: #505050;
                    }
                    QPushButton:pressed {
                        background-color: #606060;
                    }
                    QSlider::groove:horizontal {
                        border: 1px solid #555;
                        background: #2b2b2b;
                        height: 10px;
                        border-radius: 4px;
                    }
                    QSlider::handle:horizontal {
                        background: #0078d4;
                        border: 1px solid #555;
                        width: 18px;
                        margin: -2px 0;
                        border-radius: 3px;
                    }
                    QListWidget {
                        background-color: #2b2b2b;
                        color: #ffffff;
                        border: 1px solid #555555;
                    }
                    QListWidget::item:selected {
                        background-color: #0078d4;
                    }
                    QSplitter::handle {
                        background-color: #555555;
                    }
                """
            },
            "blue": {
                "name": "蓝色主题",
                "description": "清新的蓝色主题",
                "style": """
                    QMainWindow {
                        background-color: #e6f3ff;
                        color: #003366;
                    }
                    QMenuBar {
                        background-color: #cce7ff;
                        color: #003366;
                        border-bottom: 1px solid #99ccff;
                    }
                    QMenuBar::item {
                        background-color: transparent;
                        padding: 4px 8px;
                    }
                    QMenuBar::item:selected {
                        background-color: #b3d9ff;
                    }
                    QMenu {
                        background-color: #cce7ff;
                        color: #003366;
                        border: 1px solid #99ccff;
                    }
                    QMenu::item:selected {
                        background-color: #b3d9ff;
                    }
                    QStatusBar {
                        background-color: #cce7ff;
                        color: #003366;
                        border-top: 1px solid #99ccff;
                    }
                    QTextEdit {
                        background-color: #ffffff;
                        color: #003366;
                        border: 1px solid #99ccff;
                        selection-background-color: #66b3ff;
                    }
                    QScrollArea {
                        background-color: #f0f8ff;
                        border: 1px solid #99ccff;
                    }
                    QLabel {
                        color: #003366;
                    }
                    QPushButton {
                        background-color: #b3d9ff;
                        color: #003366;
                        border: 1px solid #66b3ff;
                        padding: 5px 10px;
                        border-radius: 3px;
                    }
                    QPushButton:hover {
                        background-color: #99ccff;
                    }
                    QPushButton:pressed {
                        background-color: #80bfff;
                    }
                    QSlider::groove:horizontal {
                        border: 1px solid #99ccff;
                        background: white;
                        height: 10px;
                        border-radius: 4px;
                    }
                    QSlider::handle:horizontal {
                        background: #0066cc;
                        border: 1px solid #004499;
                        width: 18px;
                        margin: -2px 0;
                        border-radius: 3px;
                    }
                """
            },
            "green": {
                "name": "绿色主题",
                "description": "自然的绿色主题",
                "style": """
                    QMainWindow {
                        background-color: #f0fff0;
                        color: #006600;
                    }
                    QMenuBar {
                        background-color: #e6ffe6;
                        color: #006600;
                        border-bottom: 1px solid #ccffcc;
                    }
                    QMenuBar::item {
                        background-color: transparent;
                        padding: 4px 8px;
                    }
                    QMenuBar::item:selected {
                        background-color: #d9ffd9;
                    }
                    QMenu {
                        background-color: #e6ffe6;
                        color: #006600;
                        border: 1px solid #ccffcc;
                    }
                    QMenu::item:selected {
                        background-color: #d9ffd9;
                    }
                    QStatusBar {
                        background-color: #e6ffe6;
                        color: #006600;
                        border-top: 1px solid #ccffcc;
                    }
                    QTextEdit {
                        background-color: #ffffff;
                        color: #006600;
                        border: 1px solid #ccffcc;
                        selection-background-color: #99ff99;
                    }
                    QScrollArea {
                        background-color: #f8fff8;
                        border: 1px solid #ccffcc;
                    }
                    QLabel {
                        color: #006600;
                    }
                    QPushButton {
                        background-color: #d9ffd9;
                        color: #006600;
                        border: 1px solid #99ff99;
                        padding: 5px 10px;
                        border-radius: 3px;
                    }
                    QPushButton:hover {
                        background-color: #ccffcc;
                    }
                    QPushButton:pressed {
                        background-color: #b3ffb3;
                    }
                    QSlider::groove:horizontal {
                        border: 1px solid #ccffcc;
                        background: white;
                        height: 10px;
                        border-radius: 4px;
                    }
                    QSlider::handle:horizontal {
                        background: #009900;
                        border: 1px solid #006600;
                        width: 18px;
                        margin: -2px 0;
                        border-radius: 3px;
                    }
                """
            },
            "purple": {
                "name": "紫色主题",
                "description": "优雅的紫色主题",
                "style": """
                    QMainWindow {
                        background-color: #f8f0ff;
                        color: #4a0080;
                    }
                    QMenuBar {
                        background-color: #f0e6ff;
                        color: #4a0080;
                        border-bottom: 1px solid #d9ccff;
                    }
                    QMenuBar::item {
                        background-color: transparent;
                        padding: 4px 8px;
                    }
                    QMenuBar::item:selected {
                        background-color: #e6d9ff;
                    }
                    QMenu {
                        background-color: #f0e6ff;
                        color: #4a0080;
                        border: 1px solid #d9ccff;
                    }
                    QMenu::item:selected {
                        background-color: #e6d9ff;
                    }
                    QStatusBar {
                        background-color: #f0e6ff;
                        color: #4a0080;
                        border-top: 1px solid #d9ccff;
                    }
                    QTextEdit {
                        background-color: #ffffff;
                        color: #4a0080;
                        border: 1px solid #d9ccff;
                        selection-background-color: #cc99ff;
                    }
                    QScrollArea {
                        background-color: #faf8ff;
                        border: 1px solid #d9ccff;
                    }
                    QLabel {
                        color: #4a0080;
                    }
                    QPushButton {
                        background-color: #e6d9ff;
                        color: #4a0080;
                        border: 1px solid #cc99ff;
                        padding: 5px 10px;
                        border-radius: 3px;
                    }
                    QPushButton:hover {
                        background-color: #d9ccff;
                    }
                    QPushButton:pressed {
                        background-color: #ccb3ff;
                    }
                    QSlider::groove:horizontal {
                        border: 1px solid #d9ccff;
                        background: white;
                        height: 10px;
                        border-radius: 4px;
                    }
                    QSlider::handle:horizontal {
                        background: #8000ff;
                        border: 1px solid #6600cc;
                        width: 18px;
                        margin: -2px 0;
                        border-radius: 3px;
                    }
                """
            }
        }
        
        # 加载保存的主题配置
        self.load_theme_config()
    
    def get_available_themes(self):
        """获取可用主题列表"""
        return [(theme_id, theme_data["name"], theme_data["description"]) 
                for theme_id, theme_data in self.themes.items()]
    
    def get_current_theme(self):
        """获取当前主题"""
        return self.current_theme
    
    def apply_theme(self, theme_id):
        """应用指定主题"""
        if theme_id not in self.themes:
            return False
        
        try:
            # 应用样式表
            style = self.themes[theme_id]["style"]
            self.main_window.setStyleSheet(style)
            
            # 更新当前主题
            self.current_theme = theme_id
            
            # 保存主题配置
            self.save_config()
            
            # 发送主题改变信号
            self.theme_changed.emit(theme_id)
            
            return True
        except Exception as e:
            print(f"应用主题失败: {e}")
            return False
    
    def load_config(self):
        """从文件加载主题配置"""
        try:
            if os.path.exists(self.config_file):
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                    self.current_theme = config.get('current_theme', 'default')
                    self.custom_themes.update(config.get('custom_themes', {}))
        except Exception as e:
            print(f"加载主题配置失败: {e}")
    
    def save_config(self):
        """保存主题配置到文件"""
        config = {
            'current_theme': self.current_theme,
            'custom_themes': self.custom_themes
        }
        
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(config, f, indent=2, ensure_ascii=False)
        except Exception as e:
            print(f"保存主题配置失败: {e}")
    
    def create_theme_dialog(self):
        """创建主题设置对话框"""
        from PyQt6.QtWidgets import QMessageBox
        
        dialog = QDialog(self.main_window)
        dialog.setWindowTitle("主题设置")
        dialog.setFixedSize(400, 300)
        
        layout = QVBoxLayout()
        
        # 主题选择
        theme_group = QGroupBox("选择主题")
        theme_layout = QVBoxLayout()
        
        self.theme_combo = QComboBox()
        self.theme_combo.addItems(list(self.themes.keys()))
        self.theme_combo.setCurrentText(self.current_theme)
        theme_layout.addWidget(self.theme_combo)
        
        theme_group.setLayout(theme_layout)
        layout.addWidget(theme_group)
        
        # 按钮
        button_layout = QHBoxLayout()
        apply_btn = QPushButton("应用")
        ok_btn = QPushButton("确定")
        cancel_btn = QPushButton("取消")
        
        def apply_theme():
            selected_theme = self.theme_combo.currentText()
            self.set_theme(selected_theme)
            self.apply_theme()
            QMessageBox.information(dialog, "成功", "主题已应用！")
        
        def accept_dialog():
            apply_theme()
            dialog.accept()
        
        apply_btn.clicked.connect(apply_theme)
        ok_btn.clicked.connect(accept_dialog)
        cancel_btn.clicked.connect(dialog.reject)
        
        button_layout.addWidget(apply_btn)
        button_layout.addWidget(ok_btn)
        button_layout.addWidget(cancel_btn)
        
        layout.addLayout(button_layout)
        dialog.setLayout(layout)
        
        return dialog
    
    def load_theme_config(self):
        """加载主题配置"""
        try:
            if os.path.exists(self.config_file):
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                    self.current_theme = config.get("current_theme", "default")
        except Exception as e:
            print(f"加载主题配置失败: {e}")
            self.current_theme = "default"
    
    def reset_to_default(self):
        """重置为默认主题"""
        return self.apply_theme("default")
    
    def add_custom_theme(self, theme_id, name, description, style):
        """添加自定义主题"""
        self.themes[theme_id] = {
            "name": name,
            "description": description,
            "style": style
        }
        return True
    
    def remove_custom_theme(self, theme_id):
        """移除自定义主题"""
        if theme_id in ["default", "dark", "blue", "green", "purple"]:
            return False  # 不能删除内置主题
        
        if theme_id in self.themes:
            del self.themes[theme_id]
            if self.current_theme == theme_id:
                self.apply_theme("default")
            return True
        return False